package com.tapstitch.scm.pms.web.filter;

import com.bluebuck.sso.client.SsoClient;
import com.bluebuck.sso.client.admin.auth.model.LoginUser;
import com.bluebuck.sso.client.admin.auth.service.LoginService;
import com.bluebuck.sso.client.model.scope.DsUserData;
import com.tapstitch.scm.common.core.context.LoginUserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置上下文用户信息
 */
@Slf4j
@Component
public class WebUserContextInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        LoginUser loginUser = loginService.getLoginUser();
        LoginUserContext.Context context = LoginUserContext.getContext();
        context.setCurrentUser(loginUser);
        if (loginUser != null) {
            DsUserData userData = SsoClient.getUserData(loginUser.getUsername(), null, "warehouse_code");
            context.setUserData(userData);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LoginUserContext.setContext(null);
    }
}
